package com.chen.auth.provider;

import com.chen.auth.service.impl.AuthUserServiceImpl;
import com.chen.base.utils.SpringContextHolder;
import com.chen.common.security.token.MobileAuthenticationToken;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;

@Setter
@Slf4j
public class MobileAuthenticationProvider implements AuthenticationProvider {

    /**
     * 手机验证码登录-用户身份信息提供者
     */
    @Override
    public Authentication authenticate(Authentication authentication) {
        MobileAuthenticationToken authenticationToken = (MobileAuthenticationToken) authentication;
        String mobile = (String) authenticationToken.getPrincipal();
        String code = (String) authenticationToken.getCredentials();

        AuthUserServiceImpl authUserServiceImpl = SpringContextHolder.getBean(AuthUserServiceImpl.class);
        UserDetails user = authUserServiceImpl.loadUserByPhone(mobile);
        if (user == null) {
            throw new OAuth2Exception("账号不存在，请注册后再试!");
        }

        MobileAuthenticationToken authenticationResult = new MobileAuthenticationToken(user, code, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }
}